package com.zimmor.mq.rocket.delay;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author:zimmor
 * @Date: 2021/11/18 15:22
 * @Description 消费者之负载均衡模式
 * @version: 1.0.0
 */

public class Consumer {
    public static void main(String[] args) throws Exception {
        //1.创建消费者，设置消费者groupId
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group4");
        //2.设置namesrv地址
        consumer.setNamesrvAddr("192.168.204.128:9876;192.168.204.129:9876");
        //3.订阅topic和tag
        consumer.subscribe("delayTopic", "tag1");
        //设置消费模式为负载均衡模式，这也是consumer默认的消费模式，不设置模式也是这个模式
        consumer.setMessageModel(MessageModel.CLUSTERING);
        //4.注册监听，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
//                    System.out.println(messageExt);
//                    System.out.println("========================");
//                    System.out.println(new String(messageExt.getBody()));
                    System.out.println("==========");
                    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(messageExt.getStoreTimestamp()))+" 接收完毕");
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5.启动consumer
        consumer.start();
        System.out.println("消费者启动");
    }
}
